/**
 * 性能验证工具
 * 用于验证DataLineage组件的性能优化效果
 */

interface PerformanceMetrics {
  componentName: string;
  renderCount: number;
  initialLoadTime: number;
  memoryUsage?: number;
  passed: boolean;
  issues: string[];
}

class PerformanceValidator {
  private metrics = new Map<string, PerformanceMetrics>();
  private startTime = 0;
  private renderCountPattern = /🔄 (\w+) 渲染次数: (\d+)/;

  /**
   * 开始性能监控
   */
  startMonitoring(componentName: string): void {
    this.startTime = performance.now();
    
    // 初始化指标
    this.metrics.set(componentName, {
      componentName,
      renderCount: 0,
      initialLoadTime: 0,
      passed: false,
      issues: [],
    });

    console.log(`📊 开始监控 ${componentName} 组件性能...`);
  }

  /**
   * 记录渲染次数
   */
  recordRender(componentName: string, renderCount: number): void {
    const metrics = this.metrics.get(componentName);
    if (metrics) {
      metrics.renderCount = Math.max(metrics.renderCount, renderCount);
      this.metrics.set(componentName, metrics);
    }
  }

  /**
   * 完成监控并生成报告
   */
  finishMonitoring(componentName: string): PerformanceMetrics {
    const endTime = performance.now();
    const metrics = this.metrics.get(componentName);
    
    if (!metrics) {
      throw new Error(`未找到组件 ${componentName} 的性能指标`);
    }

    metrics.initialLoadTime = endTime - this.startTime;

    // 获取内存使用情况（如果支持）
    if ('memory' in performance) {
      const memInfo = (performance as any).memory;
      metrics.memoryUsage = memInfo.usedJSHeapSize / 1024 / 1024; // MB
    }

    // 性能评估
    this.evaluatePerformance(metrics);

    return metrics;
  }

  /**
   * 评估性能指标
   */
  private evaluatePerformance(metrics: PerformanceMetrics): void {
    const issues: string[] = [];

    // 渲染次数检查
    const maxRenders = 3;
    if (metrics.renderCount > maxRenders) {
      issues.push(`渲染次数过多: ${metrics.renderCount}次 (期望: ≤${maxRenders}次)`);
    }

    // 加载时间检查
    const maxLoadTime = 2000; // 2秒
    if (metrics.initialLoadTime > maxLoadTime) {
      issues.push(`初始加载时间过长: ${metrics.initialLoadTime.toFixed(0)}ms (期望: ≤${maxLoadTime}ms)`);
    }

    // 内存使用检查
    if (metrics.memoryUsage && metrics.memoryUsage > 100) {
      issues.push(`内存使用过高: ${metrics.memoryUsage.toFixed(1)}MB (期望: ≤100MB)`);
    }

    metrics.issues = issues;
    metrics.passed = issues.length === 0;
  }

  /**
   * 生成性能报告
   */
  generateReport(componentName: string): string {
    const metrics = this.metrics.get(componentName);
    if (!metrics) {
      return `❌ 未找到组件 ${componentName} 的性能数据`;
    }

    let report = `\n📊 ${componentName} 性能报告\n`;
    report += `${'='.repeat(50)}\n`;
    report += `渲染次数: ${metrics.renderCount}次\n`;
    report += `加载时间: ${metrics.initialLoadTime.toFixed(0)}ms\n`;
    
    if (metrics.memoryUsage) {
      report += `内存使用: ${metrics.memoryUsage.toFixed(1)}MB\n`;
    }
    
    report += `测试结果: ${metrics.passed ? '✅ 通过' : '❌ 失败'}\n`;

    if (metrics.issues.length > 0) {
      report += `\n⚠️ 发现的问题:\n`;
      metrics.issues.forEach(issue => {
        report += `  - ${issue}\n`;
      });
    }

    if (metrics.passed) {
      report += `\n🎉 性能优化成功！组件渲染效率良好。\n`;
    } else {
      report += `\n💡 优化建议:\n`;
      report += `  - 使用React.memo优化组件重新渲染\n`;
      report += `  - 检查useEffect依赖项是否过多\n`;
      report += `  - 使用useMemo和useCallback缓存计算结果\n`;
      report += `  - 避免在渲染过程中创建新对象\n`;
    }

    return report;
  }

  /**
   * 清理监控数据
   */
  clear(): void {
    this.metrics.clear();
  }
}

// 创建全局实例
export const performanceValidator = new PerformanceValidator();

/**
 * DataLineage组件专用性能测试
 */
export const validateDataLineagePerformance = async (): Promise<PerformanceMetrics> => {
  const componentName = 'DataLineage';
  
  performanceValidator.startMonitoring(componentName);
  
  // 监听控制台输出来捕获渲染次数
  const originalLog = console.log;
  let maxRenderCount = 0;

  console.log = (...args: any[]) => {
    const message = args[0];
    if (typeof message === 'string' && message.includes('🔄 DataLineage 渲染次数:')) {
      const match = message.match(/渲染次数: (\d+)/);
      if (match) {
        const renderCount = parseInt(match[1], 10);
        maxRenderCount = Math.max(maxRenderCount, renderCount);
        performanceValidator.recordRender(componentName, maxRenderCount);
      }
    }
    return originalLog.apply(console, args);
  };

  // 等待组件加载完成
  await new Promise(resolve => setTimeout(resolve, 3000));

  // 恢复原始console.log
  console.log = originalLog;

  const metrics = performanceValidator.finishMonitoring(componentName);
  const report = performanceValidator.generateReport(componentName);
  
  console.log(report);
  
  return metrics;
};

// 在开发环境下暴露到window对象
if (process.env.NODE_ENV === 'development') {
  (window as any).performanceValidator = performanceValidator;
  (window as any).validateDataLineagePerformance = validateDataLineagePerformance;
}
